import Router from 'koa-router'
import goods from './dbs/goods'

const router = new Router({
  prefix: '/goods'
})

router.post('/add', async (ctx) => {
  const { title, itemList } = ctx.request.body
  const mitemList = itemList.toString().split(' ')
  const fresult = await goods.findOne({ title })
  const s = []
  let uresult = ''
  let flag
  if (fresult) {
    for (let i = 0; i < mitemList.length; i++) {
      if (flag) {
        s.push(mitemList[i])
      }
      flag = 1
      for (let j = 0; j < fresult.itemList.length; j++) {
        if (fresult.itemList[j] === mitemList[i]) {
          flag = 0
          break
        }
      }
    }
    if (!s.length) {
      uresult = await goods.updateOne({ title }, { $push: { itemList } })
    } else {
      uresult = await goods.updateOne({ title }, { $push: { itemList: s } })
    }
    if (uresult) {
      ctx.body = {
        code: 1,
        msg: '更新数据库成功'
      }
    }
  } else {
    const cresult = await goods.create({ title, itemList: mitemList })
    if (cresult) {
      ctx.body = {
        code: 1,
        msg: '插入数据库成功'
      }
    }
  }
})

router.get("/delete", async (ctx) => {
  const { title, item } = ctx.query
  if (item) {
    const result = await goods.updateOne({ title }, { $pull: { "itemList": item } })
    if (result) {
      ctx.body = {
        code: 1,
        msg: '删除商品成功'
      }
    }
  } else {
    const result = await goods.remove({ title })
    if (result.ok && result.deletedCount) {
      ctx.body = {
        code: 1,
        msg: '删除商品类型成功'
      }
    } else {
      ctx.body = {
        code: -1,
        msg: '未找到需要删除的商品'
      }
    }
  }
})

router.get('/getTypes', async (ctx) => {
  const itemList = await goods.find({})
  ctx.body = {
    itemList
  }
})

export default router
